<template>
  <div class="profile-edit-page">
    <div class="page-container">
      <!-- 返回按钮 -->
      <div class="back-button">
        <el-button @click="$router.back()" :icon="ArrowLeft">
          返回
        </el-button>
      </div>

      <!-- 编辑表单 -->
      <div class="edit-form-container">
        <div class="form-header">
          <h2>编辑个人资料</h2>
          <p>完善您的个人信息，让其他用户更好地了解您</p>
        </div>

        <el-form
          ref="formRef"
          :model="profileForm"
          :rules="formRules"
          label-width="100px"
          size="large"
        >
          <!-- 头像上传 -->
          <el-form-item label="头像">
            <div class="avatar-upload">
              <el-avatar :size="80" :src="profileForm.avatarUrl">
                <el-icon><User /></el-icon>
              </el-avatar>
              <el-upload
                ref="uploadRef"
                :show-file-list="false"
                :before-upload="beforeAvatarUpload"
                :on-success="handleAvatarSuccess"
                action="/api/upload/avatar"
                accept="image/*"
              >
                <el-button size="small" :icon="Camera">更换头像</el-button>
              </el-upload>
            </div>
          </el-form-item>

          <!-- 基本信息 -->
          <div class="form-section">
            <h3>基本信息</h3>
            
            <el-form-item label="昵称" prop="nickname">
              <el-input
                v-model="profileForm.nickname"
                placeholder="请输入昵称"
                maxlength="20"
                show-word-limit
                clearable
              />
            </el-form-item>

            <el-form-item label="性别">
              <el-radio-group v-model="profileForm.gender">
                <el-radio :label="0">保密</el-radio>
                <el-radio :label="1">男</el-radio>
                <el-radio :label="2">女</el-radio>
              </el-radio-group>
            </el-form-item>

            <el-form-item label="邮箱" prop="email">
              <el-input
                v-model="profileForm.email"
                placeholder="请输入邮箱"
                clearable
              />
            </el-form-item>

            <el-form-item label="手机号" prop="phone">
              <el-input
                v-model="profileForm.phone"
                placeholder="请输入手机号"
                maxlength="11"
                clearable
              />
            </el-form-item>
          </div>

          <!-- 地区信息 -->
          <div class="form-section">
            <h3>地区信息</h3>
            
            <el-form-item label="国家">
              <el-input
                v-model="profileForm.country"
                placeholder="请输入国家"
                clearable
              />
            </el-form-item>

            <el-form-item label="省份">
              <el-input
                v-model="profileForm.province"
                placeholder="请输入省份"
                clearable
              />
            </el-form-item>

            <el-form-item label="城市">
              <el-input
                v-model="profileForm.city"
                placeholder="请输入城市"
                clearable
              />
            </el-form-item>
          </div>

          <!-- 个人简介 -->
          <div class="form-section">
            <h3>个人简介</h3>
            
            <el-form-item label="个人简介">
              <el-input
                v-model="profileForm.remark"
                type="textarea"
                :rows="4"
                placeholder="介绍一下您自己，分享您对剪纸艺术的理解和感悟..."
                maxlength="500"
                show-word-limit
              />
            </el-form-item>
          </div>


          <!-- 操作按钮 -->
          <el-form-item>
            <div class="form-actions">
              <el-button type="primary" @click="handleSubmit" :loading="saving" size="large">
                <el-icon><Check /></el-icon>
                保存修改
              </el-button>
              <el-button @click="handleReset" size="large">
                <el-icon><Refresh /></el-icon>
                重置
              </el-button>
              <el-button @click="$router.push('/profile')" size="large">
                <el-icon><Close /></el-icon>
                取消
              </el-button>
            </div>
          </el-form-item>
        </el-form>
      </div>

      <!-- 账户安全 -->
      <div class="security-section">
        <div class="section-header">
          <h3><el-icon><Lock /></el-icon> 账户安全</h3>
        </div>

        <div class="security-items">
          <div class="security-item">
            <div class="item-info">
              <div class="item-title">登录密码</div>
              <div class="item-description">安全性高的密码可以使账号更安全</div>
            </div>
            <div class="item-action">
              <el-button @click="showPasswordDialog = true" :icon="Edit">
                修改密码
              </el-button>
            </div>
          </div>


        </div>
      </div>
    </div>

    <!-- 修改密码对话框 -->
    <el-dialog v-model="showPasswordDialog" title="修改密码" width="400px">
      <el-form ref="passwordFormRef" :model="passwordForm" :rules="passwordRules" label-width="100px">
        <el-form-item label="当前密码" prop="oldPassword">
          <el-input
            v-model="passwordForm.oldPassword"
            type="password"
            placeholder="请输入当前密码"
            show-password
          />
        </el-form-item>

        <el-form-item label="新密码" prop="newPassword">
          <el-input
            v-model="passwordForm.newPassword"
            type="password"
            placeholder="请输入新密码（6-20位）"
            show-password
          />
        </el-form-item>

        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="passwordForm.confirmPassword"
            type="password"
            placeholder="请再次输入新密码"
            show-password
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showPasswordDialog = false">取消</el-button>
          <el-button type="primary" @click="handlePasswordChange" :loading="passwordLoading">
            确定修改
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import {
  ArrowLeft, User, Camera, Check, Refresh, Close, Lock, Edit
} from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'
import { authApi } from '@/api'

const router = useRouter()
const userStore = useUserStore()

// 表单引用
const formRef = ref<FormInstance>()
const passwordFormRef = ref<FormInstance>()

// 状态
const saving = ref(false)
const showPasswordDialog = ref(false)
const passwordLoading = ref(false)

// 个人资料表单
const profileForm = reactive({
  nickname: '',
  avatarUrl: '',
  gender: 0,
  email: '',
  phone: '',
  country: '',
  province: '',
  city: '',
  language: 'zh-CN',
  remark: ''
})


// 密码修改表单
const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 表单验证规则
const formRules: FormRules = {
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' },
    { min: 2, max: 20, message: '昵称长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  email: [
    { 
      pattern: /^[^\s@]+@[^\s@]+\.[^\s@]+$/, 
      message: '请输入正确的邮箱格式', 
      trigger: 'blur' 
    }
  ],
  phone: [
    { 
      pattern: /^1[3-9]\d{9}$/, 
      message: '请输入正确的手机号格式', 
      trigger: 'blur' 
    }
  ]
}

// 密码验证规则
const passwordRules: FormRules = {
  oldPassword: [
    { required: true, message: '请输入当前密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 初始化表单数据
const initFormData = () => {
  const userInfo = userStore.userInfo
  if (userInfo) {
    Object.assign(profileForm, {
      nickname: userInfo.nickname || '',
      avatarUrl: userInfo.avatarUrl || '',
      gender: userInfo.gender || 0,
      email: userInfo.email || '',
      phone: userInfo.phone || '',
      country: userInfo.country || '',
      province: userInfo.province || '',
      city: userInfo.city || '',
      language: userInfo.language || 'zh-CN',
      remark: userInfo.remark || ''
    })
  }
}

// 头像上传处理
const beforeAvatarUpload = (file: File) => {
  const isImage = file.type.startsWith('image/')
  const isLt5M = file.size / 1024 / 1024 < 5

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过 5MB!')
    return false
  }
  return true
}

const handleAvatarSuccess = (response: any) => {
  if (response.code === 200) {
    profileForm.avatarUrl = response.data.url
    ElMessage.success('头像上传成功')
  } else {
    ElMessage.error('头像上传失败')
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    saving.value = true

    // 构建更新数据
    const updateData = {
      nickname: profileForm.nickname,
      avatarUrl: profileForm.avatarUrl,
      gender: profileForm.gender,
      email: profileForm.email || undefined,
      phone: profileForm.phone || undefined,
      country: profileForm.country || undefined,
      province: profileForm.province || undefined,
      city: profileForm.city || undefined,
      language: profileForm.language,
      remark: profileForm.remark || undefined
    }

    await userStore.updateUserInfo(updateData)
    ElMessage.success('个人资料更新成功')
    router.push('/profile')
  } catch (error) {
    console.error('更新个人资料失败:', error)
  } finally {
    saving.value = false
  }
}

// 重置表单
const handleReset = () => {
  initFormData()
  ElMessage.info('已重置为原始数据')
}

// 修改密码
const handlePasswordChange = async () => {
  if (!passwordFormRef.value) return

  try {
    await passwordFormRef.value.validate()
    passwordLoading.value = true

    await userStore.changePassword({
      oldPassword: passwordForm.oldPassword,
      newPassword: passwordForm.newPassword,
      confirmPassword: passwordForm.confirmPassword
    })

    ElMessage.success('密码修改成功，请重新登录')
    showPasswordDialog.value = false
    
    // 清空密码表单
    Object.assign(passwordForm, {
      oldPassword: '',
      newPassword: '',
      confirmPassword: ''
    })

    // 跳转到登录页
    setTimeout(() => {
      userStore.logout()
      router.push('/login')
    }, 1500)
  } catch (error) {
    console.error('修改密码失败:', error)
  } finally {
    passwordLoading.value = false
  }
}


onMounted(() => {
  initFormData()
})
</script>

<style scoped>
.profile-edit-page {
  min-height: 100vh;
  background: #f5f5f5;
}

.page-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.back-button {
  margin-bottom: 20px;
}

/* 编辑表单 */
.edit-form-container {
  background: #fff;
  border-radius: 12px;
  padding: 32px;
  margin-bottom: 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.form-header {
  text-align: center;
  margin-bottom: 32px;
}

.form-header h2 {
  font-size: 28px;
  font-weight: bold;
  color: #333;
  margin-bottom: 8px;
}

.form-header p {
  color: #666;
  font-size: 16px;
}

/* 头像上传 */
.avatar-upload {
  display: flex;
  align-items: center;
  gap: 16px;
}

/* 表单区块 */
.form-section {
  margin: 32px 0;
  padding: 24px 0;
  border-top: 1px solid #f0f0f0;
}

.form-section:first-child {
  border-top: none;
  padding-top: 0;
}

.form-section h3 {
  font-size: 18px;
  font-weight: bold;
  color: #333;
  margin-bottom: 20px;
  position: relative;
  padding-left: 12px;
}

.form-section h3::before {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 4px;
  height: 16px;
  background: #ff9800;
  border-radius: 2px;
}


/* 表单操作 */
.form-actions {
  display: flex;
  gap: 16px;
  justify-content: center;
  padding-top: 20px;
  border-top: 1px solid #f0f0f0;
}

/* 安全设置 */
.security-section {
  background: #fff;
  border-radius: 12px;
  padding: 32px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.section-header h3 {
  font-size: 20px;
  font-weight: bold;
  color: #333;
  margin-bottom: 24px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.security-items {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.security-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  background: #f9f9f9;
  border-radius: 8px;
  transition: all 0.3s;
}

.security-item:hover {
  background: #f0f0f0;
}

.item-info {
  flex: 1;
}

.item-title {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin-bottom: 4px;
}

.item-description {
  font-size: 14px;
  color: #666;
}

.item-action {
  margin-left: 20px;
}

/* 对话框样式 */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-container {
    padding: 16px;
  }

  .edit-form-container,
  .security-section {
    padding: 24px 20px;
  }

  .form-header h2 {
    font-size: 24px;
  }

  .form-actions {
    flex-direction: column;
    align-items: stretch;
  }

  .security-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }

  .item-action {
    margin-left: 0;
    align-self: stretch;
  }

  .item-action .el-button {
    width: 100%;
  }

}

/* 表单样式调整 */
:deep(.el-form-item__label) {
  font-weight: 500;
  color: #333;
}

:deep(.el-textarea__inner) {
  resize: vertical;
}

:deep(.el-radio-group) {
  display: flex;
  gap: 20px;
}

:deep(.el-select) {
  width: 100%;
}

:deep(.el-checkbox) {
  margin-right: 0;
}

:deep(.el-upload) {
  display: block;
}
</style>
